package main.java.com.silence.controller.intercepter;

import com.silence.constant.AttributeConstant;
import com.silence.constant.ViewNameConstant;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Author: Silence
 * Date: 2017/6/7 15:23
 * 登录权限拦截
 */
public class LoginIntercepter implements HandlerInterceptor {

    /**
     * Handler执行之前调用这个方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        if (session.getAttribute(AttributeConstant.IS_LOGIN) != null
                && (Integer) session.getAttribute(AttributeConstant.IS_LOGIN) == 1
                && session.getAttribute(AttributeConstant.LOGIN_USER_INFO) != null){

            return true;
        } else
            response.sendRedirect(ViewNameConstant.LOGIN);
        return false;
    }

    /**
     * Handler执行之后，ModelAndView返回之前调用这个方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * Handler执行完成之后调用这个方法
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
